﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

namespace D3DSS.FormUI
{
    public class IPHelper
    {
        public static Tuple<int,int> GetRoomIP()
        {
            var roomIP = new Tuple<int, int>(0, 0);

            var p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();

            p.StandardInput.WriteLine(" netstat -an ");
            p.StandardInput.WriteLine("exit");

            var reader = p.StandardOutput;
            string strAllInfo = "";
            var localInfos = new List<string>();
            string strLine = reader.ReadLine();
            int i = 0;
            while (!reader.EndOfStream)
            {
                strAllInfo += strLine + "\r\n";

                i++;

                if (i >= 9)
                {
                    if (strLine.Trim().Length > 0)
                    {
                        strLine = strLine.Trim();
                        Regex regex = new Regex(@"\s+");
                        string[] strArr = regex.Split(strLine);
                        if (strArr.Length >= 3)
                            localInfos.Add(strArr[2]);
                    }
                }
                strLine = reader.ReadLine();
            }
            p.WaitForExit();
            p.Close();
            reader.Close();

            var rooms = localInfos.Where(l => l.Contains(":1119")).ToList();
            if (rooms != null && rooms.Count > 0)
            {
                var room = rooms.SingleOrDefault(r => !r.Contains("193:1119"));
                if (!string.IsNullOrWhiteSpace(room))
                {
                    roomIP = new Tuple<int, int>(int.Parse(room.Split(':')[0].Split('.')[2]), int.Parse(room.Split(':')[0].Split('.')[3]));
                }
            }

            return roomIP;
        }
    }
}
